package com.example.ssm.utils;

import cn.hutool.core.util.IdUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileLocalUtil {
    private static final Path ROOT = Paths.get("D:/code/upload").toAbsolutePath().normalize();

    /**
     * 保存到本地，返回相对路径 /upload/新文件名
     */
    public static String save(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件为空");
        }
        String ext = getExt(file.getOriginalFilename());
        String newName = IdUtil.fastUUID() + ext;
        try {
            Files.createDirectories(ROOT);
            Path target = ROOT.resolve(newName);
            file.transferTo(target);
            // 返回供前端拼接的虚拟路径
            return "/upload/" + newName;
        } catch (IOException e) {
            throw new RuntimeException("文件写入失败", e);
        }
    }

    private static String getExt(String origin) {
        if (origin == null || !origin.contains(".")) {
            return "";
        }
        return origin.substring(origin.lastIndexOf('.'));
    }
}